package com.ssy.lingxi.marketing.controller.web;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import com.ssy.lingxi.common.controller.BaseController;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.marketing.api.model.constant.MkFeignConstants;
import com.ssy.lingxi.marketing.api.model.request.ActivityGoodsQuantityCheckRequest;
import com.ssy.lingxi.marketing.api.model.request.CartActivityPriceRequest;
import com.ssy.lingxi.marketing.model.vo.activity.response.CartActivityPriceResponse;
import com.ssy.lingxi.marketing.model.vo.coupon.request.MobileGoodsCartRequest;
import com.ssy.lingxi.marketing.model.vo.coupon.request.MobileProductDetailTagReq;
import com.ssy.lingxi.marketing.model.vo.coupon.request.MobileShopCouponListRequest;
import com.ssy.lingxi.marketing.model.vo.coupon.request.ReceiveCouponRequest;
import com.ssy.lingxi.marketing.model.vo.coupon.response.MobileCouponDetailCanUseResponse;
import com.ssy.lingxi.marketing.model.vo.coupon.response.MobileCouponResponse;
import com.ssy.lingxi.marketing.model.vo.coupon.response.MobileProductDetailTagResp;
import com.ssy.lingxi.marketing.model.vo.coupon.response.ReceiveCouponResponse;
import com.ssy.lingxi.marketing.service.IActivityPriceCalculateService;
import com.ssy.lingxi.marketing.service.IMobileActivityGoodsService;
import com.ssy.lingxi.marketing.service.IMobileCouponService;
import com.ssy.lingxi.marketing.service.feign.IMemberFeignService;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignQueryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @menu Web-代理下单相关
 * @author yzc
 * @version 2.0.0
 * @date 2021/9/6
 */
@Slf4j
@RestController
@RequestMapping("/marketing/web/agent")
public class WebAgentController extends BaseController {

    @Resource
    private IMobileActivityGoodsService mobileActivityGoodsService;
    @Resource
    private IActivityPriceCalculateService activityPriceCalculateService;

    @Resource
    private IMobileCouponService mobileCouponService;
    @Resource
    private IMemberFeignService memberFeignService;


    /**
     * 校验会员关系以及身份对调
     * @param headers
     * @return
     */
    private UserLoginCacheDTO buildAgentUser(HttpHeaders headers){
        UserLoginCacheDTO vendorUser=getSysUser();
        String memberId = headers.getFirst(MkFeignConstants.MK_AGENT_MEMBER_ID);
        String roleId=headers.getFirst(MkFeignConstants.MK_AGENT_ROLE_ID);
        if(!StringUtils.hasLength(memberId)||!StringUtils.hasLength(roleId)){
            throw new BusinessException(ResponseCode.PARAM_NOT_EXIST);
        }else if(!NumberUtil.isLong(memberId)||!NumberUtil.isLong(roleId)){
            throw new BusinessException(ResponseCode.PARAM_NOT_EXIST);
        }
        UserLoginCacheDTO agentUser=new UserLoginCacheDTO();
        agentUser.setMemberId(Long.parseLong(memberId));
        agentUser.setMemberRoleId(Long.parseLong(roleId));
        //校验供采关系
        MemberFeignVO feignVO=new MemberFeignVO();
        feignVO.setMemberId(vendorUser.getMemberId());
        feignVO.setRoleId(vendorUser.getMemberRoleId());
        Wrapper<List<MemberFeignQueryVO>> listWrapper = memberFeignService.listAllLowerMembers(feignVO);
        if(listWrapper.getCode()!=ResponseCode.SUCCESS.getCode()||CollectionUtil.isEmpty(listWrapper.getData())){
            throw new BusinessException(ResponseCode.PARAM_NOT_EXIST);
        }
        List<MemberFeignQueryVO> collect = listWrapper.getData().stream().filter(o -> o.getMemberId().equals(agentUser.getMemberId())&&o.getRoleId().equals(agentUser.getMemberRoleId())).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(collect)) {
            throw new BusinessException(ResponseCode.PARAM_NOT_EXIST);
        }
        agentUser.setCompany(collect.get(0).getMemberName());
        return agentUser;
    }

    private void isSelf(Long memberId,Long roleId){
        UserLoginCacheDTO vendorUser=getSysUser();
        if(!vendorUser.getMemberId().equals(memberId)||!vendorUser.getMemberRoleId().equals(roleId)){
            log.warn("代客下单权限不足,vendorUser:{}:{}, buyerUser:{}:{}",vendorUser.getMemberId(),vendorUser.getMemberRoleId(),memberId,roleId);
            throw new BusinessException(ResponseCode.DATA_AUTH_NOT_ALLOWED);
        }
    }


    /**
     * 校验购买数量【加入购物车的商品】
     **/
    @RequestMapping(value = "/activity/goods/check/quantity", method = RequestMethod.POST)
    public Wrapper<Double> checkQuantity(@RequestHeader HttpHeaders headers, @Valid @RequestBody ActivityGoodsQuantityCheckRequest request) {
        isSelf(request.getUpperMemberId(),request.getUpperRoleId());
        return activityPriceCalculateService.checkQuantityByAddCart(buildAgentUser(headers), request);
    }

    /**
     * 计算购物车商品活动价
     **/
    @RequestMapping(value = "/activity/goods/price/calculate", method = RequestMethod.POST)
    public Wrapper<List<CartActivityPriceResponse>> priceCalculate(@RequestHeader HttpHeaders headers,@Valid @RequestBody List<CartActivityPriceRequest> request) {
        if (CollectionUtil.isEmpty(request)) {
            return Wrapper.success();
        }
        isSelf(request.get(0).getUpperMemberId(),request.get(0).getUpperRoleId());
        //代客下单过滤拼团
        request.forEach(o ->o.setJoinGroup(Boolean.FALSE));
        return activityPriceCalculateService.calculateActivityPrice(buildAgentUser(headers), request);
    }

    /**
     * 查询活动sku商品详情活动标签
     **/
    @RequestMapping(value = "/activity/goods/detail/tag", method = RequestMethod.POST)
    public Wrapper<MobileProductDetailTagResp> getActivityGoodsProductDetailTag(@RequestHeader HttpHeaders headers,@Valid @RequestBody MobileProductDetailTagReq request) {
        isSelf(request.getMemberId(),request.getRoleId());
        //代客下单过滤拼团
        request.setFilterGroup(Boolean.TRUE);
        return mobileActivityGoodsService.getActivityGoodsProductDetailTag(buildAgentUser(headers), request);
    }


    /**
     * 提交订单 - 选择的优惠券列表
     **/
    @RequestMapping(value = "/coupon/list/by/order", method = RequestMethod.POST)
    public Wrapper<List<MobileCouponDetailCanUseResponse>> listOrderCouponDetail(@RequestHeader HttpHeaders headers,@Valid @RequestBody MobileGoodsCartRequest request) {
        isSelf(request.getGoodsList().get(0).getMemberId(),request.getGoodsList().get(0).getRoleId());
        return mobileCouponService.listOrderCouponDetail(buildAgentUser(headers), request);
    }

    /**
     * 进货单领券 - 店铺优惠券列表
     */
    @RequestMapping(value = "/coupon/list/by/shop", method = RequestMethod.GET)
    public Wrapper<List<MobileCouponResponse>> listShopCoupon(@RequestHeader HttpHeaders headers,@Valid MobileShopCouponListRequest request) {
        isSelf(request.getMemberId(),request.getRoleId());
        return mobileCouponService.listShopCoupon(buildAgentUser(headers), request);
    }

    /**
     * 用户领取优惠券
     **/
    @RequestMapping(value = "/coupon/receive", method = RequestMethod.POST)
    public Wrapper<ReceiveCouponResponse> receiveCoupon(@RequestHeader HttpHeaders headers,@Valid @RequestBody ReceiveCouponRequest request) {
        return mobileCouponService.receiveCoupon(buildAgentUser(headers), request);
    }
}
